<?php

namespace addons\yunfood\controller;

use addons\yunfood\library\Logic;
use addons\yunfood\library\Super;
use addons\yunfood\model\Feedback as FeedbackModel;
use think\Db;
use think\Exception;

/**
 * 意见反馈接口
 */
class Feedback extends BaseApi
{
    // 提交反馈
    public function submit()
    {
        // 参数校验
        $data = $this->request->post();
//        $validate = new Validate([
//            'content' => 'require',
//        ]);
//        if (! $validate->check($data)) {
//            $this->error($validate->getError());
//        }

        // 保存数据
        $feedback = new FeedbackModel();
        $photos = $data['photos'];
        if ($photos) {
            $images = [];
            foreach ($photos as $item) {
                $images[] = str_replace(request()->domain(), '', $item['url']);
            }
            $data['photos'] = implode(',', $images);
        } else {
            $data['photos'] = '';
        }
        $feedback->data($data);
//        $member->data(Super::arrayGetSet($data, [
//            'content',
//        ]));
        $feedback->user_id = $this->userId;
        $feedback->openid = $this->memberData->openid ?? '';
        $feedback->status = FeedbackModel::STATUS_NORMAL;
        $feedback->allowField(true);

        // 事务处理
        try {
            Db::transaction(function () use ($feedback) {
                // 保存数据
                $feedback->save();
            });
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('success', ['id' => $feedback->id]);
    }

    // 获取记录列表
    public function getRecordList()
    {
        // 数据列表
        $result = FeedbackModel::where(['user_id' => $this->userId])
            ->order('id DESC')
            ->paginate($this->request->post('page_size', 10), false);
        $result = Logic::getPageData($result, [
            'id',
            'type',
            'type_text',
            'content',
            'status',
            'status_text' => 'statusText',
            'created_at',
        ]);

        $this->success('success', $result);
    }

    // 获取记录详情
    public function getRecordDetail()
    {
        $recordId = $this->request->post('id');
        if (! $member = FeedbackModel::where(['id' => $recordId, 'user_id' => $this->userId])->find()) {
            $this->error('反馈不存在');
        }

        $result = Super::arrayGetSet($member, [
            'id',
            'type',
            'type_text',
            'content',
            'photos'       => 'photoList',
            'reply_content',
            'reply_photos' => 'replyPhotoList',
            'reply_time',
            'status',
            'status_text',
            'updated_at',
            'created_at',
        ]);

        $this->success('success', $result);
    }
}
